package com.mytrip.service.impl;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.mytrip.base.service.impl.BaseManagerImpl;
import com.mytrip.dao.AddressBooksDAO;
import com.mytrip.dao.AreaBizTongchengDAO;
import com.mytrip.dao.AreaTongchengDAO;
import com.mytrip.dao.CityChainTongchengDAO;
import com.mytrip.dao.FlightCityDAO;
import com.mytrip.dao.FlightCompanyDAO;
import com.mytrip.dao.OrderFlightDAO;
import com.mytrip.dao.OrderHotelDAO;
import com.mytrip.dao.OrderMemberDAO;
import com.mytrip.model.AddressBooks;
import com.mytrip.model.AreaBizTongcheng;
import com.mytrip.model.AreaBizTongchengExample;
import com.mytrip.model.AreaTongcheng;
import com.mytrip.model.AreaTongchengExample;
import com.mytrip.model.City;
import com.mytrip.model.CityChainTongcheng;
import com.mytrip.model.CityChainTongchengExample;
import com.mytrip.model.FlightCity;
import com.mytrip.model.FlightCityExample;
import com.mytrip.model.FlightCompany;
import com.mytrip.model.FlightCompanyExample;
import com.mytrip.model.OrderFlight;
import com.mytrip.model.OrderFlightExample;
import com.mytrip.model.OrderHotel;
import com.mytrip.model.OrderHotelExample;
import com.mytrip.service.OrderManager;
import com.mytrip.util.Caches;
import com.mytrip.util.Constant;
import com.mytrip.util.HttpUtil;
import com.mytrip.util.PageInfo;
import com.mytrip.util.TongchengUtil;
import com.mytrip.vo.HotelInfo;
import com.mytrip.webapp.filter.CtxSessionBag;

public class OrderManagerImpl extends BaseManagerImpl implements OrderManager{

	private OrderFlightDAO orderFlightDAO;

	private OrderHotelDAO orderHotelDAO;

	private OrderMemberDAO orderMemberDAO;

	private FlightCityDAO flightCityDAO;

	private FlightCompanyDAO flightCompanyDAO;

	private AddressBooksDAO addressBooksDAO;

	private AreaTongchengDAO areaTongchengDAO;

	private AreaBizTongchengDAO areaBizTongchengDAO;

	private CityChainTongchengDAO cityChainTongchengDAO;

	public void setAreaTongchengDAO(AreaTongchengDAO areaTongchengDAO){
		this.areaTongchengDAO = areaTongchengDAO;
	}

	public void setAreaBizTongchengDAO(AreaBizTongchengDAO areaBizTongchengDAO){
		this.areaBizTongchengDAO = areaBizTongchengDAO;
	}

	public void setCityChainTongchengDAO(CityChainTongchengDAO cityChainTongchengDAO){
		this.cityChainTongchengDAO = cityChainTongchengDAO;
	}

	public void setAddressBooksDAO(AddressBooksDAO addressBooksDAO){
		this.addressBooksDAO = addressBooksDAO;
	}

	public void setOrderFlightDAO(OrderFlightDAO orderFlightDAO){
		this.orderFlightDAO = orderFlightDAO;
	}

	public void setOrderHotelDAO(OrderHotelDAO orderHotelDAO){
		this.orderHotelDAO = orderHotelDAO;
	}

	public void setOrderMemberDAO(OrderMemberDAO orderMemberDAO){
		this.orderMemberDAO = orderMemberDAO;
	}

	public void setFlightCityDAO(FlightCityDAO flightCityDAO){
		this.flightCityDAO = flightCityDAO;
	}

	public void setFlightCompanyDAO(FlightCompanyDAO flightCompanyDAO){
		this.flightCompanyDAO = flightCompanyDAO;
	}

	@Override
	public List<FlightCity> queryAllFlightCity(){
		FlightCityExample example = new FlightCityExample();
		example.setOrderByClause("city_name asc");
		return flightCityDAO.selectByExample(example);
	}

	@Override
	public String queryFlightByApi(String fromCity, String toCity, String fromDate){
		String kjyouId = Constant.getCommonConf("kjyouId");
		String res = HttpUtil.get("http://www.kuaijieair.net/jipiao/port/s.php?s=/act/searchlist/fromcity/" + fromCity
				+ "/tocity/" + toCity + "/fromdate/" + fromDate + "/uid/" + kjyouId + "/back/tojson/");
		return res;
	}

	@Override
	public FlightCity queryFlightCityByCity3code(String city3code){
		FlightCityExample example = new FlightCityExample();
		example.createCriteria().andCity3codeEqualTo(city3code);
		List<FlightCity> res = flightCityDAO.selectByExample(example);
		return (res != null && res.size() > 0) ? res.get(0) : null;
	}

	@Override
	public List<FlightCompany> queryAllFlightCompany(){
		FlightCompanyExample example = new FlightCompanyExample();
		example.createCriteria().andCompanyIsdelEqualTo(Byte.valueOf("1"));
		example.setOrderByClause("company_code asc");
		return flightCompanyDAO.selectByExample(example);
	}

	@Override
	public String queryFlightPATByApi(String fromCity, String toCity, String flightNo, String departureDate,
			String carrier, String code, String price, String isTj, String tjId, String checkKey){
		String kjyouId = Constant.getCommonConf("kjyouId");

		Map<String, String> params = new HashMap<String, String>();
		params.put("BoardPoint", fromCity);
		params.put("OffPoint", toCity);
		params.put("FlightNo", flightNo);
		params.put("fromDate", departureDate);
		params.put("Carrier", carrier);
		params.put("Code", code);
		params.put("Price", price);
		params.put("uid", kjyouId);
		params.put("isTj", isTj);
		if ("0".equals(isTj)) {
			params.put("tjId", "");
		} else if ("1".equals(isTj)) {
			params.put("tjId", tjId);
		}
		params.put("CheckKey", checkKey);
		params.put("act", "checkPrice");

		String res = HttpUtil.post("http://www.kuaijieair.com/flight_search/jipiao/port/OrderInfo.php", params);
		return res;
	}

	@Override
	public String confirmOrder(String fromCity, String toCity, String flightNo, String departureDate,
			String departureTime, String arrivalDate, String arrivalTime, String carrier, String code, String price,
			String airportTax, String fuelSurTax, String isTj, String tjId, String checkKey, String peopleStr,
			Integer addressBooksId){
		String kjyouId = Constant.getCommonConf("kjyouId");

		Map<String, String> params = new HashMap<String, String>();
		params.put("BoardPoint", fromCity);
		params.put("OffPoint", toCity);
		params.put("FlightNo", flightNo);
		params.put("fromDate", departureDate);
		params.put("FromTime", departureTime.replace(":", ""));
		params.put("Todate", arrivalDate);
		params.put("Totime", arrivalTime.replace(":", ""));
		params.put("Carrier", carrier);
		params.put("Code", code);
		params.put("Price", price);
		params.put("AirportTax", airportTax);
		params.put("FuelSurTax", fuelSurTax);
		params.put("uid", kjyouId);
		params.put("isTj", isTj);
		if ("0".equals(isTj)) {
			params.put("tjId", "");
		} else if ("1".equals(isTj)) {
			params.put("tjId", tjId);
		}
		params.put("CheckKey", checkKey);
		params.put("act", "createOrder");
		params.put("PeopleStr", peopleStr);

		String res = HttpUtil.post("http://www.kuaijieair.com/flight_search/jipiao/port/OrderInfo.php", params);

		if (res != null && !"".equals(res)) {
			OrderFlight orderFlight = new OrderFlight();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			try {
				JSONObject resObj = JSONArray.fromObject(URLDecoder.decode(res, "UTF-8")).getJSONObject(0);
				String peopleName = resObj.getJSONArray("People").getString(0);
				String cret = "1".equals(resObj.getString(peopleName)) ? "成人" : "儿童";
				String pnrNo = resObj.getString("pnrNo");
				String tx = resObj.getString("Tx");
				String tc = resObj.getString("Tc");
				String orderId = resObj.getString("orderid");

				BigDecimal payFee = BigDecimal.valueOf(Long.valueOf(resObj.get("payPrice") + ""));
				orderFlight.setPayFee(payFee);

				// 是否保险
				boolean ins = "1".equals(peopleStr.split("_")[5]);
				BigDecimal orderFee = new BigDecimal(price);
				orderFee = orderFee.add(new BigDecimal(airportTax));
				orderFee = orderFee.add(new BigDecimal(fuelSurTax));
				if (ins) {
					orderFee = orderFee.add(BigDecimal.valueOf(20));
				}
				orderFlight.setOrderFee(orderFee);

				if (payFee.longValue() > orderFee.longValue()) {
					throw new RuntimeException("payFee > orderFee, it's not allowed!");
				}

				orderFlight.setFlightTime(sdf.parse(departureDate + " " + departureTime));
				orderFlight.setArriveTime(sdf.parse(arrivalDate + " " + arrivalTime));
				orderFlight.setAirline(carrier);
				orderFlight.setFlightNumber(flightNo);
				orderFlight.setOrderTime(new Date());
				orderFlight.setOrderStatus(OrderFlight.ORDER_STATUS_INIT);
				orderFlight.setPeopleInfo(peopleName + "(" + cret + ")");
				orderFlight.setPnrNo(pnrNo);
				orderFlight.setTx(tx);
				orderFlight.setTc(tc);
				orderFlight.setOrderId(orderId);
				orderFlight.setUid(CtxSessionBag.getSessionBag().getUserinfo().getId());
				orderFlight.setFromPort(fromCity);
				orderFlight.setToPort(toCity);

				AddressBooks addressBooks = addressBooksDAO.selectByPrimaryKey(addressBooksId);
				orderFlight.setDeliveryAddress(addressBooks.getAddress());
				orderFlight.setConsignee(addressBooks.getConsignee());
				orderFlight.setConsigneePhone(addressBooks.getPhone());
				orderFlight.setDeliveryZipcode(addressBooks.getZipcode());

				return orderFlightDAO.insert(orderFlight).toString();
			} catch (Exception e) {
				log.warn("", e);
			}
		}

		return null;
	}

	@Override
	public List<OrderFlight> queryOrderFlight(int from, int size){
		Integer uid = CtxSessionBag.getSessionBag().getUserinfo().getId();
		OrderFlightExample example = new OrderFlightExample();
		example.setOrderByClause("order_time desc limit " + from + "," + size);
		example.createCriteria().andUidEqualTo(uid);
		return orderFlightDAO.selectByExample(example);
	}

	@Override
	public int queryOrderFlightCnt(){
		Integer uid = CtxSessionBag.getSessionBag().getUserinfo().getId();
		OrderFlightExample example = new OrderFlightExample();
		example.createCriteria().andUidEqualTo(uid);
		return orderFlightDAO.countByExample(example);
	}

	@Override
	public List<OrderHotel> queryOrderHotel(int from, int size){
		Integer uid = CtxSessionBag.getSessionBag().getUserinfo().getId();
		OrderHotelExample example = new OrderHotelExample();
		example.setOrderByClause("order_time desc limit " + from + "," + size);
		example.createCriteria().andUidEqualTo(uid);
		return orderHotelDAO.selectByExample(example);
	}

	@Override
	public int queryOrderHotelCnt(){
		Integer uid = CtxSessionBag.getSessionBag().getUserinfo().getId();
		OrderHotelExample example = new OrderHotelExample();
		example.createCriteria().andUidEqualTo(uid);
		return orderHotelDAO.countByExample(example);
	}

	@Override
	public City queryHotelCityByTongchengId(Integer tongchengId){
		for (City city : Caches.cityList) {
			Integer _a = city.getTongchengCityId();
			if (_a != null && _a.equals(tongchengId)) {
				return city;
			}
		}
		return null;
	}

	@Override
	public List<AreaBizTongcheng> queryHotelAreaBizByCity(Integer cityId){
		AreaBizTongchengExample example = new AreaBizTongchengExample();
		example.createCriteria().andCityIdEqualTo(cityId);
		return areaBizTongchengDAO.selectByExample(example);
	}

	@Override
	public List<AreaTongcheng> queryHotelAreaByCity(Integer cityId){
		AreaTongchengExample example = new AreaTongchengExample();
		example.createCriteria().andCityIdEqualTo(cityId);
		return areaTongchengDAO.selectByExample(example);
	}

	@Override
	public List<CityChainTongcheng> queryHotelChainByCity(Integer cityId){
		CityChainTongchengExample example = new CityChainTongchengExample();
		example.createCriteria().andCityIdEqualTo(cityId);
		return cityChainTongchengDAO.selectByExample(example);
	}

	@Override
	public void queryHotelByApi(String cityId, String fromDate, String toDate, String key, String priceRange,
			String area, String areaBiz, String chain, PageInfo<HotelInfo> page){

		Hashtable<String, String> ht = new Hashtable<String, String>(); // 将参数放入Hashtable中，便于操作
		Calendar calendar = Calendar.getInstance();
		Date date = calendar.getTime();

		SimpleDateFormat ymdhmsf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String reqTime = ymdhmsf.format(date);

		ht.put("version", Constant.getCommonConf("tongcheng.version")); // 接口协议版本号，详见接口协议文档
		ht.put("accountId", Constant.getCommonConf("tongcheng.accountId")); // API帐户ID(小写)，待申请审批通过后发放
		ht.put("accountKey", Constant.getCommonConf("tongcheng.accountKey")); // API帐户密钥，待申请审批通过后发放
		ht.put("serviceName", "GetHotelList"); // 调用接口的方法名称
		ht.put("reqTime", reqTime); // 当前日期

		String url = "http://tcopenapi.17usoft.com/handlers/hotel/QueryHandler.ashx"; // 请求URL地址

		StringBuilder strRequest = new StringBuilder(128); // 请求XML字符串
		strRequest.append("<?xml version='1.0' encoding='utf-8' standalone='yes'?>");
		strRequest.append("<request>");
		strRequest.append("<header>");
		strRequest.append("<version>" + ht.get("version") + "</version>");
		strRequest.append("<accountID>" + ht.get("accountId") + "</accountID>");
		strRequest.append("<serviceName>" + ht.get("serviceName") + "</serviceName>");
		try {
			strRequest.append("<digitalSign>" + TongchengUtil.createDigitalSign(ht) + "</digitalSign>");
		} catch (Exception e) {
			log.warn("", e);
		}
		strRequest.append("<reqTime>" + ht.get("reqTime") + "</reqTime>");
		strRequest.append("</header>");
		strRequest.append("<body>");

		strRequest.append("<clientIp>212.222.55.12</clientIp>");
		strRequest.append("<cityId>" + cityId + "</cityId>");
		strRequest.append("<page>" + page.getCurrentPage() + "</page>");
		strRequest.append("<pageSize>" + page.getPageSize() + "</pageSize>");
		strRequest.append("<comeDate>" + fromDate + "</comeDate>");
		strRequest.append("<leaveDate>" + toDate + "</leaveDate>");
		strRequest.append("<sortType>4</sortType>");

		if (key != null && !"".equals(key.trim())) {
			strRequest.append("<keyword>" + key.trim() + "</keyword>");
			strRequest.append("<searchFields>hotelName,address</searchFields>");
		}

		if (priceRange != null && !"".equals(priceRange)) {
			strRequest.append("<priceRange>" + priceRange + "</priceRange>");
		}

		if (area != null && !"".equals(area)) {
			strRequest.append("<sectionId>" + area + "</sectionId>");
		}

		if (areaBiz != null && !"".equals(areaBiz)) {
			strRequest.append("<bizSectionId>" + areaBiz + "</bizSectionId>");
		}

		if (chain != null && !"".equals(chain)) {
			strRequest.append("<chainId>" + chain + "</chainId>");
		}

		strRequest.append("</body>");
		strRequest.append("</request>");

		String strResponse = null;
		try {
			strResponse = TongchengUtil.callUrl(url, strRequest.toString());
			// System.out.println(strResponse);

			Document doc = DocumentHelper.parseText(strResponse);
			Element rootElt = doc.getRootElement(); // 获取根节点

			if ("0".equals(rootElt.element("header").elementText("rspType"))) {
				Element extInfoOfImageList = rootElt.element("body").element("extInfoOfImageList");
				String imageBaseUrl = extInfoOfImageList.elementText("imageBaseUrl");

				Element hotelList = rootElt.element("body").element("hotelList");

				page.setAllSize(Integer.valueOf(hotelList.attributeValue("totalCount")).intValue());

				List<HotelInfo> res = new ArrayList<HotelInfo>();
				Iterator hotelIter = hotelList.elementIterator("hotel");
				while (hotelIter.hasNext()) {
					Element hotel = (Element) hotelIter.next();

					HotelInfo info = new HotelInfo();
					info.setHotelId(Integer.valueOf(hotel.elementTextTrim("hotelId")).intValue());
					info.setHotelName(hotel.elementTextTrim("hotelName"));
					info.setIntro(hotel.elementTextTrim("intro"));
					info.setOneWord(hotel.elementTextTrim("oneWord"));
					info.setAddress(hotel.elementTextTrim("address"));
					info.setImg(imageBaseUrl + hotel.elementTextTrim("img"));
					info.setRoomType(hotel.elementTextTrim("roomType"));
					if (hotel.element("chain") != null) {
						String chainName = hotel.element("chain").elementText("chainName");
						if (chainName != null) {
							info.setChainName(chainName);
						}
					}
					if (hotel.element("starRated") != null) {
						String starRatedName = hotel.element("starRated").elementText("starRatedName");
						if (starRatedName != null) {
							info.setStarRatedName(starRatedName);
						}
					}

					res.add(info);
				}

				page.setDataList(res);
			}

		} catch (Exception e) {
			log.warn("", e);
		}

	}

	@Override
	public String queryRoomsByHotelIdByApi(Integer hotelId, String fromDate, String toDate){

		Hashtable<String, String> ht = new Hashtable<String, String>(); // 将参数放入Hashtable中，便于操作
		Calendar calendar = Calendar.getInstance();
		Date date = calendar.getTime();

		SimpleDateFormat ymdhmsf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String reqTime = ymdhmsf.format(date);

		ht.put("version", Constant.getCommonConf("tongcheng.version")); // 接口协议版本号，详见接口协议文档
		ht.put("accountId", Constant.getCommonConf("tongcheng.accountId")); // API帐户ID(小写)，待申请审批通过后发放
		ht.put("accountKey", Constant.getCommonConf("tongcheng.accountKey")); // API帐户密钥，待申请审批通过后发放
		ht.put("serviceName", "GetHotelRooms"); // 调用接口的方法名称
		ht.put("reqTime", reqTime); // 当前日期

		String url = "http://tcopenapi.17usoft.com/handlers/hotel/QueryHandler.ashx"; // 请求URL地址

		StringBuilder strRequest = new StringBuilder(128); // 请求XML字符串
		strRequest.append("<?xml version='1.0' encoding='utf-8' standalone='yes'?>");
		strRequest.append("<request>");
		strRequest.append("<header>");
		strRequest.append("<version>" + ht.get("version") + "</version>");
		strRequest.append("<accountID>" + ht.get("accountId") + "</accountID>");
		strRequest.append("<serviceName>" + ht.get("serviceName") + "</serviceName>");
		try {
			strRequest.append("<digitalSign>" + TongchengUtil.createDigitalSign(ht) + "</digitalSign>");
		} catch (Exception e) {
			log.warn("", e);
		}
		strRequest.append("<reqTime>" + ht.get("reqTime") + "</reqTime>");
		strRequest.append("</header>");
		strRequest.append("<body>");

		strRequest.append("<hotelId>" + hotelId + "</hotelId>");
		strRequest.append("<comeDate>" + fromDate + "</comeDate>");
		strRequest.append("<leaveDate>" + toDate + "</leaveDate>");
		strRequest.append("<page>1</page>");
		strRequest.append("<pageSize>100</pageSize>");

		strRequest.append("</body>");
		strRequest.append("</request>");

		JSONObject res = new JSONObject();
		String strResponse = null;
		try {
			strResponse = TongchengUtil.callUrl(url, strRequest.toString());

			Document doc = DocumentHelper.parseText(strResponse);
			Element rootElt = doc.getRootElement(); // 获取根节点

			if ("0".equals(rootElt.element("header").elementText("rspType"))) {

				res.put("hotelId", rootElt.element("body").element("hotelInfo").elementTextTrim("hotelId"));
				res.put("hotelName", rootElt.element("body").element("hotelInfo").elementTextTrim("hotelName"));
				res.put("hotelType", rootElt.element("body").element("hotelInfo").elementTextTrim("hotelType"));

				Element hotelRoomList = rootElt.element("body").element("hotelRoomList");

				Iterator roomItra = hotelRoomList.elementIterator("hotelRoomInfo");
				JSONArray arr = new JSONArray();
				while (roomItra.hasNext()) {
					Element room = (Element) roomItra.next();
					JSONObject _room = new JSONObject();

					_room.put("roomTypeId", room.elementTextTrim("roomTypeId"));
					_room.put("roomName", room.elementTextTrim("roomName"));
					_room.put("roomCount", room.elementTextTrim("roomCount"));
					_room.put("bed", room.elementTextTrim("bed"));

					String allowAddBed = room.elementTextTrim("allowAddBed");
					String allowAddBedStr = "";
					if ("1".equals(allowAddBed)) {
						allowAddBedStr = "是";
					} else {
						allowAddBedStr = "否";
					}
					_room.put("allowAddBed", allowAddBedStr);

					String adsl = room.elementTextTrim("adsl");
					String adslStr = "";
					if ("1".equals(adsl)) {
						adslStr = "有(全免)";
					} else if ("2".equals(adsl)) {
						adslStr = "有(部免)";
					} else if ("3".equals(adsl)) {
						adslStr = "有(全收)";
					} else if ("4".equals(adsl)) {
						adslStr = "有(部收)";
					} else {
						adslStr = "无";
					}
					_room.put("adsl", adslStr);

					_room.put("breakfast", room.element("pricePolicyList").element("pricePolicyInfo").elementTextTrim(
							"roomBreakfast"));
					_room.put("avgAmount", room.element("pricePolicyList").element("pricePolicyInfo").elementTextTrim(
							"avgAmount"));
					_room.put("bookingCode", room.element("pricePolicyList").element("pricePolicyInfo")
							.elementTextTrim("bookingCode"));
					_room.put("roomStatusTotal", room.element("pricePolicyList").element("pricePolicyInfo")
							.elementTextTrim("roomStatusTotal"));

					arr.add(_room);
				}

				res.put("rooms", arr);
				res.put("success", "1");
			} else {
				res.put("success", "0");
			}

		} catch (Exception e) {
			log.warn("", e);
			res.put("success", "0");
		}

		return res.toString();
	}

	@Override
	public String confirmHotelOrder(String hotelId, String roomTypeId, String hotelType, String bookingCode,
			String fromDate, String toDate, String roomNum, String guestNum, String name_lx, String tel_lx,
			String name_rz, String tel_rz, String come_time, String hotelName, String roomName, String avgAmount,
			String hotelAddress){
		Hashtable<String, String> ht = new Hashtable<String, String>(); // 将参数放入Hashtable中，便于操作
		Calendar calendar = Calendar.getInstance();
		Date date = calendar.getTime();

		SimpleDateFormat ymdhmsf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String reqTime = ymdhmsf.format(date);

		ht.put("version", Constant.getCommonConf("tongcheng.version")); // 接口协议版本号，详见接口协议文档
		ht.put("accountId", Constant.getCommonConf("tongcheng.accountId")); // API帐户ID(小写)，待申请审批通过后发放
		ht.put("accountKey", Constant.getCommonConf("tongcheng.accountKey")); // API帐户密钥，待申请审批通过后发放
		ht.put("serviceName", "SubmitOrderCompletely"); // 调用接口的方法名称
		ht.put("reqTime", reqTime); // 当前日期

		String url = "http://tcopenapi.17usoft.com/handlers/hotel/orderhandler.ashx"; // 请求URL地址

		StringBuilder strRequest = new StringBuilder(128); // 请求XML字符串
		strRequest.append("<?xml version='1.0' encoding='utf-8' standalone='yes'?>");
		strRequest.append("<request>");
		strRequest.append("<header>");
		strRequest.append("<version>" + ht.get("version") + "</version>");
		strRequest.append("<accountID>" + ht.get("accountId") + "</accountID>");
		strRequest.append("<serviceName>" + ht.get("serviceName") + "</serviceName>");
		try {
			strRequest.append("<digitalSign>" + TongchengUtil.createDigitalSign(ht) + "</digitalSign>");
		} catch (Exception e) {
			log.warn("", e);
		}
		strRequest.append("<reqTime>" + ht.get("reqTime") + "</reqTime>");
		strRequest.append("</header>");
		strRequest.append("<body><order>");

		strRequest.append("<orderIP>212.25.27.144</orderIP>");
		strRequest.append("<hotelId>" + hotelId + "</hotelId>");
		strRequest.append("<roomTypeId>" + roomTypeId + "</roomTypeId>");
		strRequest.append("<bookingCode>" + bookingCode + "</bookingCode>");
		strRequest.append("<hotelType>" + hotelType + "</hotelType>");
		strRequest.append("<comeDate>" + fromDate + "</comeDate>");
		strRequest.append("<leaveDate>" + toDate + "</leaveDate>");
		strRequest.append("<roomNum>" + roomNum + "</roomNum>");
		strRequest.append("<guestNum>" + guestNum + "</guestNum>");
		int _roomNum = Integer.valueOf(roomNum);
		if (_roomNum > 1) {
			String otherGuests = "";
			for (int i = 1; i < _roomNum; i++) {
				otherGuests += name_rz + "[#1]";
				if (i + 1 < _roomNum) {
					otherGuests += ",";
				}
			}
			strRequest.append("<otherGuests>" + otherGuests + "</otherGuests>");
		}
		strRequest.append("<contactName>" + name_lx + "</contactName>");
		strRequest.append("<contactMobile>" + tel_lx + "</contactMobile>");
		strRequest.append("<guestName>" + name_rz + "</guestName>");
		strRequest.append("<guestMobile>" + tel_rz + "</guestMobile>");
		strRequest.append("<guestCredentialType>1</guestCredentialType>");

		int _come_time = Integer.parseInt(come_time);
		String comeTime = null;
		if (_come_time < 12) {
			strRequest.append("<comeType>早到</comeType>");
			if (_come_time == 6 || _come_time == 7) {
				comeTime = "6:00-8:00";
			} else if (_come_time == 8 || _come_time == 9) {
				comeTime = "8:00-10:00";
			} else if (_come_time == 10 || _come_time == 11) {
				comeTime = "10:00-12:00";
			}
		} else if (_come_time >= 12 && _come_time <= 18) {
			strRequest.append("<comeType>12:00-18:00</comeType>");
			comeTime = "12:00-18:00";
		} else if (_come_time > 18) {
			strRequest.append("<comeType>晚到</comeType>");
			if (_come_time == 19) {
				comeTime = "18:00-19:00";
			} else if (_come_time == 20) {
				comeTime = "19:00-20:00";
			} else if (_come_time == 21) {
				comeTime = "20:00-21:00";
			} else if (_come_time == 22 || _come_time == 23) {
				comeTime = "21:00-23:00";
			} else if (_come_time == 24) {
				comeTime = "23:00-24:00";
			}
		}
		if (comeTime != null) {
			strRequest.append("<comeTime>" + comeTime + "</comeTime>");
		}
		strRequest.append("<guaranteeFlag>0</guaranteeFlag>");

		strRequest.append("</order></body>");
		strRequest.append("</request>");

		JSONObject res = new JSONObject();
		String strResponse = null;
		try {
			strResponse = TongchengUtil.callUrl(url, strRequest.toString());

			Document doc = DocumentHelper.parseText(strResponse);
			Element rootElt = doc.getRootElement(); // 获取根节点

			if ("0".equals(rootElt.element("header").elementText("rspType"))) {
				String orderId = rootElt.element("body").element("order").elementTextTrim("serialId");
				if (orderId != null) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					OrderHotel orderHotel = new OrderHotel();
					orderHotel.setUid(CtxSessionBag.getSessionBag().getUserinfo().getId());
					orderHotel.setCheckInTime(sdf.parse(fromDate));
					orderHotel.setCheckOutTime(sdf.parse(toDate));
					orderHotel.setHotelAddress(hotelAddress);
					orderHotel.setHotelName(hotelName);
					orderHotel.setOrderTime(new Date());
					orderHotel.setRoomName(roomName);
					orderHotel.setRoomNum(_roomNum);
					orderHotel.setNameLx(name_lx);
					orderHotel.setTelLx(tel_lx);
					orderHotel.setNameRz(name_rz);
					orderHotel.setTelRz(tel_rz);
					orderHotel.setComeTime((_come_time <= 9 ? "0" + _come_time : _come_time) + ":00");
					orderHotel.setAvgAmount(avgAmount);
					orderHotel.setOrderId(orderId);
					orderHotelDAO.insert(orderHotel);

					res.put("success", "1");
				} else {
					res.put("success", "0");
				}
			} else {
				res.put("success", "0");
			}

		} catch (Exception e) {
			log.warn("", e);
			res.put("success", "0");
		}

		return res.toString();
	}
}
